<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="录入时间" prop="outTime">
          <el-date-picker
              v-model="queryParams.recordTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="!w-[240px]"
          />
        </el-form-item>
        <el-form-item label="旅行社名称" prop="deptId">
          <el-tree-select
            v-model="queryParams.deptId"
            placeholder="全部"
            :data="deptOptions"
            filterable
            clearable
            check-strictly
            :render-after-expand="false"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryId">
          <el-tree-select
            v-model="queryParams.categoryId"
            placeholder="全部"
            :data="categoryOptions"
            filterable
            clearable
            check-strictly
            :render-after-expand="false"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="录入人" prop="recordUserName">
          <el-input
            v-model="queryParams.recordUserName"
            placeholder="录入人"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="审核人" prop="auditUserName">
          <el-input
            v-model="queryParams.auditUserName"
            placeholder="审核人"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="审核结果" prop="auditResult">
          <dict
            v-model="queryParams.auditResult"
            code="auditResult"
            style="width: 200px"
            placeholder="全部"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-switch v-model="showStats"></el-switch><span style="margin-left: 10px;">显示统计</span>
        </el-form-item>
      </el-form>
    </div>
    <div class="search-bar" v-if="showStats">
      <div class="stats-container">
        <div v-show="noData">
          <span class="text-gray">暂无数据</span>
        </div>
        <div v-show="!noData" class="stat-item" v-for="stat in statsData" :key="stat.categoryName">
          <span class="label">{{ stat.categoryName }}</span>
          <span class="value">：{{ stat.num }}</span>
        </div>
      </div>
    </div>
    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['system:spotTicket:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['system:spotTicket:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
        <el-button
          v-hasPerm="['system:spotTicket:report']"
          type="success"
          :disabled="reportIds.length === 0"
          @click="handleReport()"
        >
          <template #icon>
            <Check />
          </template>
          发起
        </el-button>
        <el-button v-hasPerm="['system:spotTicket:word']" type="primary" @click="handleExport()">
          <template #icon>
            <Download />
          </template>
          导出
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <!--        <el-table-column-->
        <!--          key="deptId"-->
        <!--          label="旅行社Id"-->
        <!--          prop="deptId"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
          key="deptName"
          label="旅行社名称"
          prop="deptName"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <!--        <el-table-column-->
        <!--          key="categoryId"-->
        <!--          label="分类Id"-->
        <!--          prop="categoryId"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
          key="categoryName"
          label="分类名称"
          prop="categoryName"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column key="num" label="预售数量" prop="num" min-width="100" align="center" />
        <!--        <el-table-column-->
        <!--          key="recordBy"-->
        <!--          label="录入人Id"-->
        <!--          prop="recordBy"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
          key="recordUserName"
          label="录入人"
          prop="recordUserName"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          key="recordTime"
          label="录入时间"
          prop="recordTime"
          min-width="180"
          align="center"
        />
        <!--        <el-table-column-->
        <!--          key="auditBy"-->
        <!--          label="审核人Id"-->
        <!--          prop="auditBy"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
          key="auditUserName"
          label="审核人"
          prop="auditUserName"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          key="auditTime"
          label="审核时间"
          prop="auditTime"
          min-width="180"
          align="center"
        />
        <el-table-column label="审核结果" width="110" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.auditResult" code="auditResult" />
          </template>
        </el-table-column>
        <el-table-column
          key="remark"
          label="审核意见"
          prop="remark"
          min-width="200"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:spotTicket:report']"
              :disabled="scope.row.auditResult === 1 || scope.row.auditResult === 2"
              type="success"
              size="small"
              link
              @click="handleReport(scope.row.id)"
            >
              <template #icon>
                <Check />
              </template>
              发起
            </el-button>
            <el-button
              v-hasPerm="['system:spotTicket:edit']"
              :disabled="scope.row.auditResult === 1 || scope.row.auditResult === 2"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:spotTicket:delete']"
              :disabled="scope.row.auditResult === 1"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 预售票数据表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="旅行社名称" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="请选择旅行社名称"
            :data="deptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryId">
          <el-tree-select
            v-model="formData.categoryId"
            placeholder="请选择分类名称"
            :data="categoryOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="预售数量" prop="num">
          <el-input-number
            v-model="formData.num"
            placeholder="预售数量"
            :controls="false"
            :precision="0"
            maxlength="8"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="loading"  @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import DeptAPI from "@/api/system/dept";

defineOptions({
  name: "SpotTicket",
  inheritAttrs: false,
});

import SpotTicketAPI, {
  SpotTicketPageVO,
  SpotTicketForm,
  SpotTicketPageQuery,
} from "@/api/system/spot-ticket";
import SpotCategoryAPI from "@/api/system/spot-category";
import SpotRecordAPI from "@/api/system/spot-record";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const reportIds = ref<number[]>([]);
const total = ref(0);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
const categoryOptions = ref<OptionType[]>();

const now = new Date();
const startOfDay = new Date(now);
startOfDay.setHours(0, 0, 0, 0);

const endOfDay = new Date(now);
endOfDay.setHours(23, 59, 59, 999);

const format = (date: Date) => {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const mi = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${mi}:${s}`;
};
const queryParams = reactive<SpotTicketPageQuery>({
  pageNum: 1,
  pageSize: 10,
  recordTime:[format(startOfDay), format(endOfDay)]
});

// 预售票数据表格数据
const pageData = ref<SpotTicketPageVO[]>([]);
const showStats = ref(true); // 默认显示统计信息
const noData = ref(false); // 默认显示统计信息
// 统计数据
const statsData = ref<SpotTicketForm[]>([]);
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 预售票数据表单数据
const formData = reactive<SpotTicketForm>({});

// 预售票数据表单校验规则
const rules = reactive({
  deptId: [{ required: true, message: "请选择旅行社名称", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择分类名称", trigger: "blur" }],
  num: [
    { required: true, message: "请输入预售数量", trigger: "blur" },
    {
      validator: (rule: any, value: number, callback: any) => {
        if (value <= 0) {
          callback(new Error("预售数量必须大于0"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
});

/** 查询预售票数据 */
function handleQuery() {
  loading.value = true;
  noData.value = false;
  SpotTicketAPI.getCount(queryParams)
      .then((data) => {
        if (data.length === 0) {
          noData.value = true;
        } else {
          const processedData = data.map(item => ({
            categoryName: item.categoryName || '未知分类',
            num: item.num || 0
          }));
          statsData.value = processedData;
        }
      })
      .catch(() => {
        // 异常情况下也显示“暂无数据”
        statsData.value = [{categoryName: '暂无数据', num: 0}];
      });
  SpotTicketAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置预售票数据查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection
    .filter((item: any) => item.auditResult !== 1)
    .map((item: any) => item.id);
  reportIds.value = selection
    .filter((item: any) => item.auditResult === 0)
    .map((item: any) => item.id);
}

function handleReport(id?: number) {
  const ids = [id || reportIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选发起审核项");
    return;
  }

  ElMessageBox.confirm("确认将已选中的数据项发起审核?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      SpotTicketAPI.reportByIds(ids)
        .then(() => {
          ElMessage.success("发起审核成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消发起审核");
    }
  );
}

/** 打开预售票数据弹窗 */
async function handleOpenDialog(id?: number) {
  // 加载部门下拉数据源
  dialog.visible = true;
  // 加载区域下拉数据源
  deptOptions.value = await DeptAPI.getOptions();
  // 加载分类下拉数据源
  categoryOptions.value = await SpotCategoryAPI.getOptions();

  if (id) {
    dialog.title = "修改预售票数据";
    SpotTicketAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增预售票数据";
  }
}

/** 提交预售票数据表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SpotTicketAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        SpotTicketAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭预售票数据弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除预售票数据 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      SpotTicketAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function handleExport() {
  SpotTicketAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

if (onMounted) {
  onMounted(async () => {
    // 加载区域下拉数据源
    deptOptions.value = await DeptAPI.getOptions();
    // 加载分类下拉数据源
    categoryOptions.value = await SpotCategoryAPI.getOptions();
    handleQuery();
  });
}
</script>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}
:deep(.el-popper) {
  max-width: 300px;
}
</style>

<style scoped>
.stats-container {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.label {
  margin-right: 0px;
  font-size: 16px;
  color: #6331d3;
  font-weight: bold;
}

.value {
  font-size: 16px;
  color: #6331d3;
  font-weight: bold;
}
</style>
<style>
.text-gray {
  color: #999;
}
</style>
